const FoodObj = require('../modules/Food');
const uuid = require('node-uuid');
const fs = require('fs');
const path = require('path');

let FoodController = {
    get_foodInfo: async function(req, res){
        let resultDate = await FoodObj.getFoodInfo();
        res.send(resultDate);
    },
    post_foodAdd: async function(req, res){
        let data = req.body;
        let resultDate = await FoodObj.addFood(data);
        res.send(resultDate);
    },

    post_foodEdit: async function(req, res){
        let data = req.body;
        let resultDate = await FoodObj.editFood(data);
        res.send(resultDate);
    },

    post_foodDel: async function(req, res){
        let data = req.body;
        let resultDate = await FoodObj.delFood(data);
        res.send(resultDate);
    },

    post_foodImg: async function (req, res) {
        const files = req.files
        const user = JSON.parse(req.body.userData)
        let is = fs.createReadStream(files.file.path);
        const h = files.file.originalFilename.substring(files.file.originalFilename.lastIndexOf('.') + 1)
        let newFileName = uuid.v1()+'.'+h;
        const filePath = path.resolve(__dirname,'../../../public/images/' + newFileName);
        let os = fs.createWriteStream(filePath);
        is.pipe(os);
        is.on('end', function () {
            fs.unlinkSync(files.file.path);
        });
        let resultDate = await FoodObj.saveImg({
            'filesName': '/food/img?url='+newFileName,
            'food_id': user.food_id,
        });
        res.send(resultDate);
    },

    get_img: async function (req, res) {
        let data = req.query
        console.log(data);
        const filePath = path.resolve(__dirname, `../../../public/images/${data.url}`);
        // 给客户端返回一个文件流 type类型
        res.set('content-type', { "png": "image/png", "jpg": "image/jpeg" });//设置返回类型
        var stream = fs.createReadStream(filePath);
        var responseData = [];//存储文件流
        if (stream) {//判断状态
            stream.on('data', function (chunk) {
                responseData.push(chunk);
            });
            stream.on('end', function () {
                var finalData = Buffer.concat(responseData);
                res.write(finalData);
                res.end();
            });
        }
    }
}
module.exports = FoodController;